package com.jd.finance.oss.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.jd.finance.oss.exception.OSSException;
import com.jd.finance.oss.mapper.OssObjectsOriginalMapper;
import com.jd.finance.oss.model.OssObject;
import com.jd.finance.oss.model.OssObjectsOriginal;
import com.jd.finance.oss.model.User;
import com.jd.finance.oss.util.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class AsyncTaskServiceImpl implements AsyncTask {
    @Resource
    OssObjectsOriginalMapper ossObjectsOriginalMapper;

    // 异步保存原图
    @Override
    public void uploadObjectsOriginalAsync(InputStream inputStream, MultipartFile multipartFile, OssObject ossObjectCompress, String bizType, User user, long id) {
        try {
            if (Thread.currentThread().getId() == id) {
                log.info("同步上传原图uploadObjectsOriginalAsync，fileName = {}", multipartFile.getOriginalFilename());
            } else {
                log.info("异步上传原图uploadObjectsOriginalAsync，fileName = {}", multipartFile.getOriginalFilename());
            }
            long time1 = System.currentTimeMillis();
            OssObject ossObject = buildOSSObjects(bizType, user, multipartFile);
            //调用阿里云SDK上传对象
            boolean res = AliyunOSSUtils.upload(inputStream, ossObject.getObjectKey());
            if (res) {
                OssObjectsOriginal ossObjectsOriginal = new OssObjectsOriginal();
                CopyOptions copyOptions2 = new CopyOptions();
                copyOptions2.setIgnoreNullValue(true);
                copyOptions2.setIgnoreCase(false);
                BeanUtil.copyProperties(ossObject, ossObjectsOriginal, copyOptions2);
                ossObjectsOriginal.setCompressId(ossObjectCompress.getObjectId());
                //插入到数据库
                int count = ossObjectsOriginalMapper.insert(ossObjectsOriginal);
                if (count < 1) {
                    log.error("异步上传原图，对象上传时插入数据库失败：FileName = {}", multipartFile.getOriginalFilename());
                    OSSException ossException = new OSSException();
                    ossException.setErrorCode(-1);
                    ossException.setErrorMessage("异步上传原图，对象上传时插入数据库失败：FileName = " + multipartFile.getOriginalFilename());
                    throw ossException;
                }
            }
            long time2 = System.currentTimeMillis();
            log.info("异步上传原图耗时：{}", time2 - time1);
            log.info("异步上传原图耗时：{}", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss.sss"));
        } catch (Exception e) {
            log.error("异步上传原图失败", e);
        }
    }


    private OssObject buildOSSObjects(String bizType, User user, MultipartFile multipartFile) throws IOException {

        OssObject ossObject = new OssObject();

        //对象在阿里云OSS的bucket存储区中的key为：DATETIME_UUID，如：20210101020304555_6d25a684-9558-11e9-aa94-efccd7a0659b
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
        SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM");
        //objectKey = /${bizType}/${yyyy}/${yyyy-MM}/${yyyyMMddHHmmssSSS}_${uuid}
        String objectKey = bizType +
                "/" + sdfYear.format(date) +
                "/" + sdfMonth.format(date) +
                "/" + sdf.format(date) + "_" + UUID.randomUUID().toString();
        ossObject.setObjectKey(objectKey);

        //带扩展名的名称
        String fileName = multipartFile.getOriginalFilename();
        if (fileName.length() > 250) {
            //影像文件名称过长处理
            fileName = StringUtils.substring(fileName, 0, 250);
        }
        ossObject.setObjectName(fileName);

        // 对象类型，即扩展名
        String objectType = multipartFile.getContentType();
        ossObject.setObjectType(objectType);

        //对象大小
        ossObject.setObjectSize("" + multipartFile.getSize());

        //上传人ID
        ossObject.setUploadPersonnelId(Long.valueOf(user.getUid()));

        //上传人名字
        ossObject.setUploadPersonnelName(user.getUserName());

        //上传时间
        ossObject.setUploadTime(LocalDateTime.now());

        //对象状态：1存活, 2已删除
        ossObject.setStatus(OssObject.STATUS_ALIVE);

        return ossObject;
    }


}

